package com.zut.yyzx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zut.yyzx.dto.NurseRecordDTO;
import com.zut.yyzx.mapper.CustomernurseitemMapper;
import com.zut.yyzx.mapper.NurserecordMapper;
import com.zut.yyzx.pojo.Customernurseitem;
import com.zut.yyzx.pojo.Nurserecord;
import com.zut.yyzx.service.NurserecordService;
import com.zut.yyzx.utils.ResultVo;
import com.zut.yyzx.vo.NurseRecordsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class NurserecordServiceImpl extends ServiceImpl<NurserecordMapper, Nurserecord> implements NurserecordService {
    @Autowired
    private CustomernurseitemMapper customernurseitemMapper;

    @Autowired
    private NurserecordMapper nurserecordMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo addNurseRecord(Nurserecord nurserecord) throws Exception {
        //生成护理记录
         nurserecord.setIsDeleted(0);//默认生效
         boolean temp=save(nurserecord);
         //查询当前用户的护理项目余量
        QueryWrapper qw=new QueryWrapper();
        qw.eq("custormer_id",nurserecord.getCustomerId());
        qw.eq("item_id",nurserecord.getItemId());
        qw.eq("is_deleted",0);
        Customernurseitem customernurseitem=customernurseitemMapper.selectOne(qw);
        //修改用户护理项目数量
        UpdateWrapper uw=new UpdateWrapper();
        uw.set("nurse_number",customernurseitem.getNurseNumber()-nurserecord.getNursingCount()); //余量-当前护理数量
        uw.eq("custormer_id",nurserecord.getCustomerId());
        uw.eq("item_id",nurserecord.getItemId());
        uw.eq("is_deleted",0);
        int row=customernurseitemMapper.update(null,uw);
        if(!(temp && row>0)){
            throw  new Exception("护理记录生成失败");
        }
        return ResultVo.ok("护理记录生成成功");
    }

    @Override
    public ResultVo<Page<NurseRecordsVo>> queryNurseRecordsVo(NurseRecordDTO nurseRecordDTO) throws Exception {
        Page<NurseRecordsVo> page=new Page<>(nurseRecordDTO.getPageSize(),6);
        nurserecordMapper.selectNurseRecordsVo(page,nurseRecordDTO.getCustomerId());
        return ResultVo.ok(page);
    }
}
